<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\ServiceOrder;
use think\Db;

class AutoCancelServiceOrder extends Command
{
    protected function configure()
    {
        $this->setName('order:auto_cancel_service')
            ->setDescription('自动取消超时未支付的服务项目订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始处理超时未支付的服务项目订单...');
        
        // 查找超过2小时未支付的订单
        $time = time() - 7200; // 当前时间减去2小时
        $orders = ServiceOrder::where([
            'status' => ServiceOrder::STATUS_UNPAID,  // 未支付状态
            'createtime' => ['<', $time]
        ])->select();
            
        if (empty($orders)) {
            $output->writeln('没有需要处理的订单');
            return;
        }
        
        foreach ($orders as $order) {
            Db::startTrans();
            try {
                // 更新订单状态为已取消
                $order->status = ServiceOrder::STATUS_CANCEL;
                $order->save();
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order->user_id,
                    'type' => 'service',
                    'title' => '订单已取消',
                    'content' => "您的服务项目订单 {$order->order_no} 因超时未支付已自动取消",
                    'order_id' => $order->id,
                    'order_no' => $order->order_no
                ]);
                
                Db::commit();
                $output->writeln("订单 {$order->order_no} 已取消");
            } catch (\Exception $e) {
                Db::rollback();
                $output->writeln("订单 {$order->order_no} 取消失败：" . $e->getMessage());
            }
        }
        
        $output->writeln('处理完成');
    }
}